using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.SchemaReader
{
	public abstract class ColumnBase : DbObject
	{
		protected bool _isNullable = false;
		protected bool _isComputed = false;

		protected string _dataType = "";
		protected short _precision = -1;
		protected int _scale = -1;
		protected short _length = -1;

		public ColumnBase() : this("", 0) { }

		public ColumnBase(string name, int id)
			: base (name, id)
		{

		}

		public bool IsNullable
		{
			get { return _isNullable; }
			internal set { _isNullable = value; }
		}

		public bool IsComputed
		{
			get { return _isComputed; }
			internal set { _isComputed = value; }
		}

		public string DataType
		{
			get { return _dataType; }
			internal set { _dataType = value; }
		}

		public short Precision
		{
			get { return _precision; }
			internal set { _precision = value; }
		}

		public int Scale
		{
			get { return _scale; }
			internal set { _scale = value; }
		}

		public short Length
		{
			get { return _length; }
			internal set { _length = value; }
		}

		public override XmlElement CreateXmlElement(XmlDocument doc, XmlNode parent)
		{
			XmlElement el = base.CreateXmlElement(doc, parent);

			el.Attributes.Append(doc.CreateAttribute("isnullable")).Value = _isNullable.ToString();
			el.Attributes.Append(doc.CreateAttribute("iscomputed")).Value = _isComputed.ToString();
			el.Attributes.Append(doc.CreateAttribute("datatype")).Value = _dataType;
			el.Attributes.Append(doc.CreateAttribute("precision")).Value = _precision.ToString();
			el.Attributes.Append(doc.CreateAttribute("scale")).Value = _scale.ToString();
			el.Attributes.Append(doc.CreateAttribute("length")).Value = _length.ToString();

			return el;
		}

		public override void LoadXml(XmlElement el, Database db)
		{
			base.LoadXml(el, db);

			string bvalue = "";

			bvalue = el.GetAttribute("isnullable");
			if ( !bool.TryParse(bvalue, out _isNullable) )
				_isNullable = false;

			bvalue = el.GetAttribute("iscomputed");
			if ( !bool.TryParse(bvalue, out _isComputed) )
				_isComputed = false;

			_dataType = el.GetAttribute("datatype");

			string ivalue = "";

			ivalue = el.GetAttribute("precision");
			if ( !short.TryParse(ivalue, out _precision) )
				_precision = -1;

			ivalue = el.GetAttribute("scale");
			if ( !int.TryParse(ivalue, out _scale) )
				_scale = -1;

			ivalue = el.GetAttribute("length");
			if ( !short.TryParse(ivalue, out _length) )
				_length = -1;
		}
	}
}
